const HomeHttp = require("../../utils/Home")
const CartHttp = require("../../utils/cart")
Page({
  data: {
    carts:[],
        allChecked:"",
        sum:""
  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  async onLoad() {
    var res = await CartHttp.getCart();
    // console.log(res)
    var arr = res.data.res;
    var carts = [];
    arr.forEach(item => {
     var  { _id, price, name, Count, isLike, pic,title } = item;
      carts.push({
        _id,
        pic,
        name: name.slice(3,20),
        Count,
        isLike,
        price,
        title
      })
      var allChecked = carts.every(item=>{
        return item.isLike; 
      })
      this.setData({
        carts,
        allChecked
      })
    })
    this.handleSum()
  },
  handleNum(event){
    /* 通过id值,找到数组中对应的项目,将项目中的productCount更改 */
    // console.log(event.detail)
    var carts = this.data.carts;
    var {aid} = event.currentTarget.dataset;
    carts.forEach(item=>{
        if(item.id == aid)[
            item.Count =  event.detail
        ]
    })
    this.setData({
        carts
    })
    this.handleSum()

},
handleSelect(event){
    console.log(event.detail)
    var carts = this.data.carts;
    var {aid} = event.currentTarget.dataset;
    carts.forEach(item=>{
        if(item.id == aid)[
            item.isLike =  event.detail
        ]
    })
    /* 更改item的check,allCheced */
    var allChecked = carts.every(item=>{
        return item.isLike;
    })
    this.setData({
        carts,
        allChecked
    })
    this.handleSum()
},
handleAll(event){
    console.log(event.detail);
    var carts = this.data.carts;
    carts.forEach(item=>{
        item.isLike = event.detail;
    })
    this.setData({
        allChecked:event.detail,
        carts
    })
    this.handleSum()
},
handleSum(){
    var sum = 0;
    var carts = this.data.carts;
    carts.forEach(item=>{
        if(item.isLike){
            sum += (item.price)*(item.Count)   
         }
    })
    this.setData({
        sum:sum*100
    })
  },
  handleDelete(event){
    // console.log(event.currentTarget.dataset)
    var {aid} = event.currentTarget.dataset;
    var carts = this.data.carts;
    carts.forEach(item=>{
      if(item._id == aid){
        item.isLike =!item.isLike;
        if(item.isLike == false){
          var _id = item._id;
          // console.log(_id)
          var isLike = false;
          wx.request({
            url: `http://127.0.0.1:7001/likeman`,
            data: {
              id:_id,
              isLike
            },
            header: {
              'content-type': "application/x-www-form-urlencoded"
            },
            method: 'POST',
            success: function (res) {
              console.log(res);
            },
          });
        }
      }
    })
  }
})